package dbops

import (
	"gitee.com/DengAnbang/goutils/dbutils"
	"gitee.com/DengAnbang/goutils/utils"
)

type MessageBean struct {
	Id             string `json:"id"`
	ToUserId       string `json:"to_user_id"`
	MessageType    int    `json:"message_type"`
	MessageContent string `json:"message_content"`
	MessageAppend  string `json:"message_append"`
	IsRead         int    `json:"is_read"`
	Created        string `json:"created"`
}

func NewMessageBean(data map[string]string) MessageBean {
	return MessageBean{
		Id:             data["id"],
		ToUserId:       data["to_user_id"],
		MessageType:    utils.String2int(data["message_type"], 0),
		MessageContent: data["message_content"],
		MessageAppend:  data["message_append"],
		IsRead:         utils.String2int(data["is_read"], 0),
		Created:        data["created"],
	}
}
func MessageCreate(messageBean MessageBean) error {
	stmtIn, err := dbConn.Prepare(`INSERT INTO table_message (message_type,to_user_id,message_content,message_append)
		VALUES(?,?,?,?)`)
	if err != nil {
		return err
	}
	_, err = stmtIn.Exec(messageBean.MessageType, messageBean.ToUserId, messageBean.MessageContent, messageBean.MessageAppend)
	if err != nil {
		return err
	}
	_ = stmtIn.Close()
	return nil
}

//查询所有消息
func MessageSelect(userId string) ([]MessageBean, error) {
	var messageBeans = make([]MessageBean, 0)
	stmtOut, err := dbConn.Prepare(`SELECT * ,UNIX_TIMESTAMP(created) FROM table_message 
 WHERE to_user_id = ?`)
	if err != nil {
		return messageBeans, err
	}
	defer stmtOut.Close()
	rows, err := stmtOut.Query(userId)
	if err != nil {
		return messageBeans, err
	}
	for rows.Next() {
		var stringMap map[string]string
		stringMap, err = dbutils.GetRowsMap(rows)
		if err != nil {
			return messageBeans, err
		}
		messageBeans = append(messageBeans, NewMessageBean(stringMap))
	}
	return messageBeans, nil
}

//消息已读
func MessageRead(messageId string) error {
	stmtOut, err := dbConn.Prepare(`UPDATE table_message set is_read=? where id=?`)
	if err != nil {
		return err
	}
	defer stmtOut.Close()
	_, err = stmtOut.Query(1, messageId)
	if err != nil {
		return err
	}

	return nil
}

//消息删除
func MessageDelete(messageId string) error {
	stmtOut, err := dbConn.Prepare(`DELETE FROM table_message WHERE id=?`)
	if err != nil {
		return err
	}
	defer stmtOut.Close()
	_, err = stmtOut.Query(messageId)
	if err != nil {
		return err
	}
	return nil
}
